#!/usr/bin/env python
#!conding:utf-8
"""
author:Johnson
date: 2017/5/24 10:29
version: v1.0
description:
    发送邮件相关
"""
from threading import Thread
from flask_mail import Message
from flask.globals import current_app
from flask.templating import render_template
from blog import mail


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_mail(to,subject,template,**kwargs):
    """
    发送邮件
    :param to 收件人
    :param subject 标题
    :param template 模板地址,模板不要写后缀，因为发送邮件时需要两个模板，一个文本的，一个html的
    :param **kwargs 其他参数
    :return:
    """
    app = current_app._get_current_object()
    msg = Message(subject = app.config['FLASKY_MAIL_SUBJECT_PREFIX']+" "+ subject,
                  sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
    msg.body = render_template(template+".txt",**kwargs)
    msg.html = render_template(template+".html",**kwargs)
    thr = Thread(target=send_async_email,args=[app,msg],name='send mail thread')
    thr.start()
    return thr

